package cn.appsys.controller.developer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;

import cn.appsys.pojo.AppCategory;
import cn.appsys.pojo.AppInfo;
import cn.appsys.pojo.AppVersion;
import cn.appsys.pojo.DataDictionary;
import cn.appsys.pojo.DevUser;
import cn.appsys.service.developer.AppCategoryService;
import cn.appsys.service.developer.AppInfoService;
import cn.appsys.service.developer.AppVersionService;
import cn.appsys.service.developer.DataDictionaryService;
import cn.appsys.tools.Constants;
import cn.appsys.tools.PageSupport;

@RequestMapping("/dev/flatform/app")
@Controller
public class AppController {

	private Logger logger = Logger.getLogger(AppController.class);

	@Resource
	private AppInfoService appInfoService;

	@Resource
	private AppVersionService appVersionService;

	@Resource
	private AppCategoryService appCategoryService;

	@Resource
	private DataDictionaryService dataDictionaryService;

	@RequestMapping(value = "/list")
	public String getAppInfoList(Model model, HttpSession session,
			@RequestParam(value = "querySoftwareName", required = false) String _querySoftwareName,
			@RequestParam(value = "queryStatus", required = false) String _queryStatus,
			@RequestParam(value = "queryFlatformId", required = false) String _queryFlatformId,
			@RequestParam(value = "queryCategoryLevel1", required = false) String _queryCategoryLevel1,
			@RequestParam(value = "queryCategoryLevel2", required = false) String _queryCategoryLevel2,
			@RequestParam(value = "queryCategoryLevel3", required = false) String _queryCategoryLevel3,
			@RequestParam(value = "pageIndex", required = false) String pageIndex) {
		logger.debug("_querySoftwareName ======>" + _querySoftwareName);
		logger.debug("_queryStatus ======>" + _queryStatus);
		logger.debug("_queryFlatformId ======>" + _queryFlatformId);
		logger.debug("_queryCategoryLevel1 ======>" + _queryCategoryLevel1);
		logger.debug("_queryCategoryLevel2 ======>" + _queryCategoryLevel2);
		logger.debug("_queryCategoryLevel3 ======>" + _queryCategoryLevel3);
		logger.debug("pageIndex ======>" + pageIndex);

		// 将一些可能会导致后面转换值引发空指针异常的参数设置默认值
		if (_queryCategoryLevel1 == null || _queryCategoryLevel1 == "") {
			_queryCategoryLevel1 = "0";
		}
		if (_queryCategoryLevel2 == null || _queryCategoryLevel2 == "") {
			_queryCategoryLevel2 = "0";
		}
		if (_queryCategoryLevel3 == null || _queryCategoryLevel3 == "") {
			_queryCategoryLevel3 = "0";
		}
		if (_queryFlatformId == null || _queryFlatformId == "") {
			_queryFlatformId = "0";
		}
		if (_queryStatus == null || _queryStatus == "") {
			_queryStatus = "0";
		}

		// 设置页面容量
		int pageSize = Constants.pageSize;
		// 当前页码
		int currentPageNo = 1;
		// 对pageIndex的值进行简单处理
		if (pageIndex != null) {
			try {
				currentPageNo = Integer.valueOf(pageIndex);
			} catch (Exception e) {
				return "redirect:error.html";
			}
		}
		// 总数量（表）
		int totalCount = 0;
		try {
			Integer devId = ((DevUser) session.getAttribute((Constants.DEV_USER_SESSION))).getId();
			totalCount = appInfoService.getAppInfoCount(_querySoftwareName, _queryStatus, _queryFlatformId,
					_queryCategoryLevel1, _queryCategoryLevel2, _queryCategoryLevel3, devId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		PageSupport page = new PageSupport();
		page.setCurrentPageNo(currentPageNo);
		page.setPageSize(pageSize);
		page.setTotalCount(totalCount);
		// 控制首页和尾页
		if (currentPageNo < 1) {
			currentPageNo = 1;
		} else if (currentPageNo > totalCount) {
			currentPageNo = totalCount;
		}
		List<AppInfo> appInfoList = null;
		List<DataDictionary> flatFormList = null;
		List<DataDictionary> statusList = null;
		List<AppCategory> categoryLevel1List = null;
		List<AppCategory> categoryLevel2List = null;
		List<AppCategory> categoryLevel3List = null;
		try {
			Integer devId = ((DevUser) session.getAttribute((Constants.DEV_USER_SESSION))).getId();
			appInfoList = appInfoService.getAppInfoList(_querySoftwareName, _queryStatus, _queryFlatformId,
					_queryCategoryLevel1, _queryCategoryLevel2, _queryCategoryLevel3, pageSize, currentPageNo, devId);

			flatFormList = getDataDictionaries("APP_FLATFORM");
			statusList = getDataDictionaries("APP_STATUS");
			categoryLevel1List = appCategoryService.getCategoryLevelList(null);
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			if (_queryCategoryLevel2 != null && _queryCategoryLevel2 != "") {
				categoryLevel2List = getAppCategories(_queryCategoryLevel1.toString());
				model.addAttribute("categoryLevel2List", categoryLevel2List);
				if (_queryCategoryLevel3 != null && _queryCategoryLevel3 != "") {
					categoryLevel3List = getAppCategories(_queryCategoryLevel2.toString());
					model.addAttribute("categoryLevel3List", categoryLevel3List);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("appInfoList", appInfoList);
		model.addAttribute("flatFormList", flatFormList);
		model.addAttribute("statusList", statusList);
		model.addAttribute("querySoftwareName", _querySoftwareName);
		model.addAttribute("queryStatus", _queryStatus);
		model.addAttribute("queryFlatformId", _queryFlatformId);
		model.addAttribute("queryCategoryLevel1", _queryCategoryLevel1);
		model.addAttribute("queryCategoryLevel2", _queryCategoryLevel2);
		model.addAttribute("queryCategoryLevel3", _queryCategoryLevel3);
		model.addAttribute("pages", page);
		model.addAttribute("categoryLevel1List", categoryLevel1List);
		return "developer/appinfolist";
	}

	@RequestMapping(value = "/categorylevellist.json", method = RequestMethod.GET)
	@ResponseBody
	public List<AppCategory> getCategoryLevellist(Model model, @RequestParam String pid) {
		if (pid == "") {
			pid = null;
		}
		return getAppCategories(pid);
	}

	/**
	 * 回调方法
	 * 
	 * @param pid
	 * @return
	 */
	public List<AppCategory> getAppCategories(String pid) {
		return appCategoryService.getCategoryLevelList(pid);
	}

	/**
	 * 回调方法
	 * 
	 * @param tcode
	 * @return
	 */
	public List<DataDictionary> getDataDictionaries(String tcode) {
		return dataDictionaryService.getDataDictionaryList(tcode);
	}

	@RequestMapping(value = "/datadictionarylist.json", method = RequestMethod.GET)
	@ResponseBody
	public List<DataDictionary> getDataDictionaryList(Model model, @RequestParam String tcode) {
		if (tcode == "") {
			tcode = null;
		}
		return getDataDictionaries(tcode);
	}

	@RequestMapping(value = "/appinfoadd", method = RequestMethod.GET)
	public String addAppInfo() {
		return "developer/appinfoadd";
	}

	@RequestMapping(value = "/appinfoaddsave", method = RequestMethod.POST)
	public String addSaveAppInfo(AppInfo appInfo,
			@RequestParam(value = "a_logoPicPath", required = false) MultipartFile a_logoPicPath,
			HttpServletRequest request) {
		String logoPicPath = null;
		String logoLocPath = null;
		try {
			// D:/Users/AppInfoSystem/src/main/webapp/statics/uploadfiles
			// 判断文件是否为空
			if (!a_logoPicPath.isEmpty()) {
				String path = request.getSession().getServletContext()
						.getRealPath("statics" + File.separator + "uploadfiles");// 文件存放地址
				String oldFileName = a_logoPicPath.getOriginalFilename();// 原文件名
				String prefix = FilenameUtils.getExtension(oldFileName);// 原文件后缀
				int filesize = 500000;// 设置上传大小
				if (a_logoPicPath.getSize() > filesize) {// 上传大小不得超过 500KB
					request.getSession().setAttribute("fileUploadError", "* 上传大小不得超过 500KB");
					return "developer/appinfoadd";
				} else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
						|| prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")) {// 上传图片格式不正确
					logger.debug("new fileName========== " + a_logoPicPath.getName());
					File targetFile = new File(path, oldFileName);
					if (!targetFile.exists()) {
						targetFile.mkdirs();
					}
					// 保存
					try {
						a_logoPicPath.transferTo(targetFile);
						saveFile(oldFileName, targetFile);
					} catch (Exception e) {
						e.printStackTrace();
						request.getSession().setAttribute("fileUploadError", " * 上传失败！");
						return "developer/appinfoadd";
					}
				} else {
					request.getSession().setAttribute("fileUploadError", " * 上传图片格式不正确");
					return "developer/appinfoadd";
				}
				logoLocPath = path + File.separator + oldFileName;
				logoPicPath = "/AppInfoSystem/statics/uploadfiles/" + oldFileName;
			}

		} catch (Exception e) {
			e.printStackTrace();
			return "developer/appinfoadd";
		}
		Integer id = ((DevUser) request.getSession().getAttribute(Constants.DEV_USER_SESSION)).getId();
		appInfo.setCreatedBy(id);
		appInfo.setDevId(id);
		appInfo.setCreationDate(new Date());
		appInfo.setLogoLocPath(logoLocPath);
		appInfo.setLogoPicPath(logoPicPath);
		try {
			if (appInfoService.addAppInfo(appInfo)) {
				return "redirect:/dev/flatform/app/list";
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return "developer/appinfoadd";
	}

	private void saveFile(String oldFileName, File targetFile) throws FileNotFoundException, IOException {
		String path;
		try (FileInputStream input = new FileInputStream(targetFile)) {
			path = "C:/Users/FengShaZi/Workspaces/MyEclipse 2017/AppInfoSystem/src/main/webapp/statics/uploadfiles/" + oldFileName;
			File outFile = new File(path);
			try (FileOutputStream output = new FileOutputStream(outFile)) {
				byte[] b = new byte[1024 * 5];
				int len;
				while ((len = input.read(b)) != -1) {
					output.write(b, 0, len);
				}
			} catch (Exception e) {
				logger.error("保存文件出错！", e);
			}
		} catch (Exception e) {
			logger.error("将文件注入输入流出错！", e);
		}
	}

	@RequestMapping(value = "/apkexist.json", method = RequestMethod.GET)
	@ResponseBody
	public Object apkExist(@RequestParam(value = "APKName") String APKName) {
		HashMap<String, String> map = new HashMap<String, String>();
		int count = 0;
		try {
			count = appInfoService.apkExist(APKName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (APKName == null) {
			map.put("APKName", "empty");
		} else if (count > 0) {
			map.put("APKName", "exist");
		} else if (count == 0) {
			map.put("APKName", "noexist");
		}
		return JSONArray.toJSONString(map);
	}

	@RequestMapping(value = "/appinfomodify", method = RequestMethod.GET)
	public String modifyAppinfo(@RequestParam(value = "id") String id, Model model) {
		List<DataDictionary> flatFormList = null;
		AppInfo appInfo = null;
		try {
			flatFormList = getDataDictionaries("APP_FLATFORM");
			model.addAttribute("flatFormList", flatFormList);
			appInfo = appInfoService.getAppInfo(Integer.parseInt(id));
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		model.addAttribute("appInfo", appInfo);
		return "developer/appinfomodify";
	}

	@RequestMapping(value = "delfile.json", method = RequestMethod.GET)
	@ResponseBody
	public Object delFile(@RequestParam String id, @RequestParam String flag) {
		HashMap<String, String> map = new HashMap<String, String>();
		try {
			if (flag.equals("logo")) {
				AppInfo appInfo = appInfoService.getAppInfo(Integer.parseInt(id));
				String logoLocPath = appInfo.getLogoLocPath();
				String str = appInfo.getLogoPicPath();
				String logoPicPath = "C:/Users/FengShaZi/Workspaces/MyEclipse 2017/AppInfoSystem/src/main/webapp/statics/uploadfiles/"
						+ str.substring((str.lastIndexOf("/") + 1), str.length());

				if (appInfoService.delFile(Integer.parseInt(id))) {
					map.put("result", "success");
					delFiles(logoPicPath, logoLocPath);
				} else {
					map.put("result", "failed");
				}
			} else if (flag.equals("apk")) {
				AppVersion appVersion = appVersionService.getAppVersion(null, id);
				String downloadLink = "D:/Users/AppInfoSystem/src/main/webapp/statics/uploadfiles/"
						+ appVersion.getApkFileName();
				if (appVersionService.delFile(id)) {
					map.put("result", "success");
					delFiles(null, downloadLink);
				} else {
					map.put("result", "failed");
				}
			}

		} catch (Exception e) {
			logger.error(e.getMessage());
			map.put("result", "failed");
		}
		return JSONArray.toJSONString(map);
	}

	/**
	 * 用于删除文件
	 * 
	 * @param logoPicPath
	 *            相对路径
	 * @param logoLocPath
	 *            绝对路径
	 */
	private void delFiles(String logoPicPath, String logoLocPath) throws Exception {
		File file;
		if (logoPicPath != null) {
			file = new File(logoPicPath);
			if (file.exists()) {
				file.delete();
			}
		}
		if (logoLocPath != null) {
			file = new File(logoLocPath);
			if (file.exists()) {
				file.delete();
			}
		}
	}

	@RequestMapping(value = "/appinfomodifysave", method = RequestMethod.POST)
	public String modifySaveAppInfo(AppInfo appInfo,
			@RequestParam(value = "attach", required = false) MultipartFile attach, HttpServletRequest request) {
		String logoPicPath = null;
		String logoLocPath = null;
		try {
			// D:/Users/AppInfoSystem/src/main/webapp/statics/uploadfiles
			// 判断文件是否为空
			if (!attach.isEmpty()) {
				String path = request.getSession().getServletContext()
						.getRealPath("statics" + File.separator + "uploadfiles");// 文件存放地址
				String oldFileName = attach.getOriginalFilename();// 原文件名
				String prefix = FilenameUtils.getExtension(oldFileName);// 原文件后缀
				int filesize = 500000;// 设置上传大小
				if (attach.getSize() > filesize) {// 上传大小不得超过 500KB
					request.getSession().setAttribute("fileUploadError", "* 上传大小不得超过 500KB");
					return "redirect:/dev/flatform/app/appinfomodify?id=" + appInfo.getId();
				} else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
						|| prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")) {// 上传图片格式不正确
					logger.debug("new fileName========== " + attach.getName());
					File targetFile = new File(path, oldFileName);
					if (!targetFile.exists()) {
						targetFile.mkdirs();
					}
					// 保存
					try {
						attach.transferTo(targetFile);
						saveFile(oldFileName, targetFile);
					} catch (Exception e) {
						e.printStackTrace();
						request.getSession().setAttribute("fileUploadError", " * 上传失败！");
						return "redirect:/dev/flatform/app/appinfomodify?id=" + appInfo.getId();
					}
				} else {
					request.getSession().setAttribute("fileUploadError", " * 上传图片格式不正确");
					return "redirect:/dev/flatform/app/appinfomodify?id=" + appInfo.getId();
				}
				logoLocPath = path + File.separator + oldFileName;
				logoPicPath = "/AppInfoSystem/statics/uploadfiles/" + oldFileName;
				appInfo.setLogoLocPath(logoLocPath);
				appInfo.setLogoPicPath(logoPicPath);
			}

		} catch (Exception e) {
			e.printStackTrace();
			return "redirect:/dev/flatform/app/appinfomodify?id=" + appInfo.getId();
		}
		try {
			Integer id = ((DevUser) request.getSession().getAttribute(Constants.DEV_USER_SESSION)).getId();
			appInfo.setModifyBy(id);
			appInfo.setDevId(id);
			appInfo.setModifyDate(new Date());
			if (appInfoService.modifyAppInfo(appInfo)) {
				return "redirect:/dev/flatform/app/list";
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return "redirect:/dev/flatform/app/appinfomodify?id=" + appInfo.getId();
	}

	@RequestMapping(value = "/appversionadd", method = RequestMethod.GET)
	public String addAppVersion(Model model, @RequestParam(value = "id") String id) {
		List<AppVersion> appVersionList = null;
		AppVersion appVersion = new AppVersion();
		appVersion.setAppId(Integer.parseInt(id));
		try {
			appVersionList = appVersionService.getAppVersionList(id);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		model.addAttribute("appVersionList", appVersionList);
		model.addAttribute("appVersion", appVersion);
		return "developer/appversionadd";
	}

	@RequestMapping(value = "/addversionsave", method = RequestMethod.POST)
	public String addSaveVersion(AppVersion appVersion,
			@RequestParam(value = "a_downloadLink", required = false) MultipartFile attach,
			HttpServletRequest request) {
		String apkLocPath = null;
		String apkFileName = null;
		String downloadLink = null;
		try {
			// D:/Users/AppInfoSystem/src/main/webapp/statics/uploadfiles
			// 判断文件是否为空
			if (!attach.isEmpty()) {
				String path = request.getSession().getServletContext()
						.getRealPath("statics" + File.separator + "uploadfiles");// 文件存放地址
				apkFileName = attach.getOriginalFilename();// 原文件名
				String prefix = FilenameUtils.getExtension(apkFileName);// 原文件后缀
				int filesize = 500000000;// 设置上传大小
				if (attach.getSize() > filesize) {// 上传大小不得超过 500KB
					request.getSession().setAttribute("fileUploadError", "* 上传大小不得超过 500MB");
					return "redirect:/dev/flatform/app/appversionadd?id=" + appVersion.getAppId();
				} else if (prefix.equalsIgnoreCase("apk")) {// 上传apk文件格式不正确
					logger.debug("new fileName========== " + attach.getName());
					File targetFile = new File(path, apkFileName);
					if (!targetFile.exists()) {
						targetFile.mkdirs();
					}
					// 保存
					try {
						attach.transferTo(targetFile);
						saveFile(apkFileName, targetFile);
					} catch (Exception e) {
						e.printStackTrace();
						request.getSession().setAttribute("fileUploadError", " * 上传失败！");
						return "redirect:/dev/flatform/app/appversionadd?id=" + appVersion.getAppId();
					}
				} else {
					request.getSession().setAttribute("fileUploadError", " * 上传apk文件格式不正确");
					return "redirect:/dev/flatform/app/appversionadd?id=" + appVersion.getAppId();
				}
				apkLocPath = path + File.separator + apkFileName;
				downloadLink = "/AppInfoSystem/statics/uploadfiles/" + apkFileName;
				appVersion.setDownloadLink(downloadLink);
				appVersion.setApkFileName(apkFileName);
				appVersion.setApkLocPath(apkLocPath);
			}

		} catch (Exception e) {
			e.printStackTrace();
			return "redirect:/dev/flatform/app/appversionadd?id=" + appVersion.getAppId();
		}
		try {
			Integer id = ((DevUser) request.getSession().getAttribute(Constants.DEV_USER_SESSION)).getId();
			appVersion.setCreatedBy(id);
			appVersion.setCreationDate(new Date());
			if (appVersionService.addAppVersion(appVersion)) {
				appVersion = appVersionService.getAppVersion(appVersion.getAppId().toString(), null);
				if (appInfoService.updateAppInfoVersion(appVersion.getAppId(), appVersion.getId())) {
					return "redirect:/dev/flatform/app/list";
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return "redirect:/dev/flatform/app/appversionadd?id=" + appVersion.getAppId();
	}

	@RequestMapping(value = "/appversionmodify", method = RequestMethod.GET)
	public String modifyAppVersion(@RequestParam(value = "vid") String vid, @RequestParam(value = "aid") String aid,
			Model model) {
		List<AppVersion> appVersionList = null;
		AppVersion appVersion = new AppVersion();
		try {
			appVersion = appVersionService.getAppVersion(aid, vid);
			if (appVersion.getApkLocPath() != null) {
				if (appVersion.getApkFileName() == null) {
					appVersion.setApkFileName(
							appVersion.getApkLocPath().substring(appVersion.getApkLocPath().lastIndexOf("\\")+1));
					if (appVersion.getDownloadLink() == null) {
						appVersion.setDownloadLink("/AppInfoSystem/statics/uploadfiles/" + appVersion.getApkFileName());
						appVersionService.modifyAppVersion(appVersion);
						appVersion = appVersionService.getAppVersion(aid, vid);
					}
				}
			}
			appVersionList = appVersionService.getAppVersionList(aid);
			String path = "D:/Users/AppInfoSystem/src/main/webapp/statics/uploadfiles/" + appVersion.getApkFileName();
			File file = new File(path);
			if (!file.exists()) {
				file = new File(appVersion.getApkLocPath());
				saveFile(appVersion.getApkFileName(), file);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		model.addAttribute("appVersionList", appVersionList);
		model.addAttribute("appVersion", appVersion);
		return "developer/appversionmodify";
	}

	@RequestMapping(value = "/appversionmodifysave", method = RequestMethod.POST)
	public String modifySaveAppVersion(AppVersion appVersion,
			@RequestParam(value = "attach", required = false) MultipartFile attach, HttpServletRequest request) {
		String apkLocPath = null;
		String apkFileName = null;
		String downloadLink = null;
		try {
			// D:/Users/AppInfoSystem/src/main/webapp/statics/uploadfiles
			// 判断文件是否为空
			if (!attach.isEmpty()) {
				String path = request.getSession().getServletContext()
						.getRealPath("statics" + File.separator + "uploadfiles");// 文件存放地址
				apkFileName = attach.getOriginalFilename();// 原文件名
				String prefix = FilenameUtils.getExtension(apkFileName);// 原文件后缀
				int filesize = 500000000;// 设置上传大小
				if (attach.getSize() > filesize) {// 上传大小不得超过 500KB
					request.setAttribute("fileUploadError", "* 上传大小不得超过 500MB");
					return "redirect:/dev/flatform/app/appversionmodify?vid=" + appVersion.getId() + "&aid="
							+ appVersion.getAppId();
				} else if (prefix.equalsIgnoreCase("apk")) {// 上传apk文件格式不正确
					logger.debug("new fileName========== " + attach.getName());
					File targetFile = new File(path, apkFileName);
					if (!targetFile.exists()) {
						targetFile.mkdirs();
					}
					// 保存
					try {
						attach.transferTo(targetFile);
						saveFile(apkFileName, targetFile);
					} catch (Exception e) {
						e.printStackTrace();
						request.setAttribute("fileUploadError", " * 上传失败！");
						return "redirect:/dev/flatform/app/appversionmodify?vid=" + appVersion.getId() + "&aid="
								+ appVersion.getAppId();
					}
				} else {
					request.setAttribute("fileUploadError", " * 上传apk文件格式不正确");
					return "redirect:/dev/flatform/app/appversionmodify?vid=" + appVersion.getId() + "&aid="
							+ appVersion.getAppId();
				}
				apkLocPath = path + File.separator + apkFileName;
				downloadLink = "/AppInfoSystem/statics/uploadfiles/" + apkFileName;
				appVersion.setApkFileName(apkFileName);
				appVersion.setApkLocPath(apkLocPath);
				appVersion.setDownloadLink(downloadLink);
			} else {
				File file = new File(appVersion.getApkLocPath());
				saveFile(appVersion.getApkFileName(), file);
				if (appVersion.getDownloadLink().indexOf("/appId") > 0) {
					appVersion
							.setDownloadLink("/AppInfoSystem/statics/uploadfiles" + "/" + appVersion.getApkFileName());
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			return "redirect:/dev/flatform/app/appversionmodify?vid=" + appVersion.getId() + "&aid="
					+ appVersion.getAppId();
		}
		try {
			Integer id = ((DevUser) request.getSession().getAttribute(Constants.DEV_USER_SESSION)).getId();
			appVersion.setModifyBy(id);
			appVersion.setModifyDate(new Date());
			if (appVersionService.modifyAppVersion(appVersion)) {
				appVersion = appVersionService.getAppVersion(appVersion.getAppId().toString(), null);
				if (appInfoService.updateAppInfoVersion(appVersion.getAppId(), appVersion.getId())) {
					return "redirect:/dev/flatform/app/list";
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return "redirect:/dev/flatform/app/appversionmodify?vid=" + appVersion.getId() + "&aid="
				+ appVersion.getAppId();
	}

	@RequestMapping(value = "appview/{id}", method = RequestMethod.GET)
	public String viewOfAppInfo(@PathVariable String id, Model model) {
		AppInfo appInfo = null;
		List<AppVersion> appVersionList = null;
		try {
			appInfo = appInfoService.getAppInfo(Integer.parseInt(id));
			appVersionList = appVersionService.getAppVersionList(id);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		model.addAttribute("appVersionList", appVersionList);
		model.addAttribute("appInfo", appInfo);
		return "developer/appinfoview";
	}

	@RequestMapping(value = "/delapp.json", method = RequestMethod.GET)
	@ResponseBody
	public Object delApp(@RequestParam(value = "id") String id) {
		HashMap<String, String> map = new HashMap<String, String>();
		List<AppVersion> appVersions = appVersionService.getAppVersionList(id);
		for (AppVersion appVersion : appVersions) {
			String apkLocPath = appVersion.getApkLocPath();
			String downloadLink = "C:/Users/FengShaZi/Workspaces/MyEclipse 2017/AppInfoSystem/src/main/webapp/statics/uploadfiles/"
					+ appVersion.getApkFileName();
			try {
				delFiles(apkLocPath, downloadLink);
				appVersionService.delAppVersion(appVersion.getId().toString());
			} catch (Exception e) {
				logger.error(e.getMessage());
				map.put("delResult", "false");
				return JSONArray.toJSONString(map);
			}
		}
		AppInfo appInfo = null;
		try {
			appInfo = appInfoService.getAppInfo(Integer.parseInt(id));
			if (appInfo == null) {
				map.put("delResult", "notexist");
				return JSONArray.toJSONString(map);
			}
			String logoPicPath = appInfo.getLogoLocPath();
			String str = appInfo.getLogoPicPath();
			String logoLocPath=null;
			if (str!=null) {
				logoLocPath = "C:/Users/FengShaZi/Workspaces/MyEclipse 2017/AppInfoSystem/src/main/webapp/statics/uploadfiles/"
						+ str.substring((str.lastIndexOf("/") + 1), str.length());
			}
			if (appInfoService.delApp(id)) {
				map.put("delResult", "true");
				delFiles(logoPicPath, logoLocPath);
				return JSONArray.toJSONString(map);
			} else {
				map.put("delResult", "false");
				return JSONArray.toJSONString(map);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			map.put("delResult", "false");
			return JSONArray.toJSONString(map);
		}
	}

	@RequestMapping(value = "/{id}/sale.json", method = RequestMethod.PUT)
	@ResponseBody
	public Object sale(@PathVariable String id) {
		HashMap<String, String> map = new HashMap<String, String>();
		try {
			AppInfo appInfo = null;
			int appId = 0;
			try {
				appId = Integer.parseInt(id);
			} catch (NumberFormatException e) {
				logger.error(e.getMessage());
				map.put("errorCode", "param000001");
				return JSONArray.toJSONString(map);
			}
			try {
				appInfo = appInfoService.getAppInfo(appId);
				if (appInfo != null) {
					switch (appInfo.getStatus()) {
					case 2:
					case 5:
						if (appInfoService.updateAppStatus(4, appInfo.getId())) {
							map.put("resultMsg", "success");
						} else {
							map.put("resultMsg", "failed");
						}
						break;
					case 4:
						if (appInfoService.updateAppStatus(5, appInfo.getId())) {
							map.put("resultMsg", "success");
						} else {
							map.put("resultMsg", "failed");
						}
						break;
					}
				}
			} catch (Exception e) {
				logger.error(e.getMessage());
				map.put("resultMsg", "failed");
				return JSONArray.toJSONString(map);
			}
			map.put("errorCode", "0");
			return JSONArray.toJSONString(map);
		} catch (Exception e) {
			logger.error(e.getMessage());
			map.put("errorCode", "exception000001");
			return JSONArray.toJSONString(map);
		}
	}
}
